import api.RobotAPIWrapper;
import api.RobotAPIWrapperImpl;
import api.RobotAPIWrapperTester;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GuiController extends JFrame{
	protected Button forward, back, left, right, stop, speed, slow;
	private RobotAPIWrapper robot;
	
	// Need to pass robot into constructor
	public GuiController(RobotAPIWrapper r) {
		super("Robot Controller");
		robot = r;
		setSize(200,200);
		setLayout(new BorderLayout());
		forward = new Button("Forward");
		back= new Button("Back");
		left = new Button("Left");
		right = new Button("Right");
		stop = new Button("Stop");
		speed = new Button("Speed up");
		slow = new Button("Slow down");
		
		ButtonListener b = new ButtonListener();
		
		forward.addActionListener(b);
		back.addActionListener(b);
		left.addActionListener(b);
		right.addActionListener(b);
		stop.addActionListener(b);
		slow.addActionListener(b);
		speed.addActionListener(b);
		
		add(forward, BorderLayout.NORTH);
		add(back, BorderLayout.SOUTH);
		add(left, BorderLayout.WEST);
		add(right, BorderLayout.EAST);
		
		Panel p = new Panel(new BorderLayout());
		add(p, BorderLayout.CENTER);
		
		p.add(stop, BorderLayout.CENTER);
		p.add(speed, BorderLayout.NORTH);
		p.add(slow, BorderLayout.SOUTH);
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	
	private class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent evt) {
			String arg = evt.getActionCommand();
			if(arg.equals("Forward")) {
				robot.forward();
				return;
			}
			if(arg.equals("Back")) {
				robot.backward();
				return;
			}
			if(arg.equals("Left")) {
				robot.left();
				return;
			}
			if(arg.equals("Right")) {
				robot.right();
				return;
			}
			if(arg.equals("Speed up")) {
				robot.speedUp(3);
				return;
			}
			if(arg.equals("Slow down")) {
				robot.slowDown(3);
				return;
			}
			if(arg.equals("Stop")) {
				robot.stop();
				return;
			}
		}
	}
	
	public static void main(String args[])
  {
    RobotAPIWrapper rAPI;
		if(args.length > 0)
			rAPI = new RobotAPIWrapperTester();
		else 
			rAPI = new RobotAPIWrapperImpl("NXT-B", true);
    GuiController c;
    if(rAPI.isReady())
      c = new GuiController(rAPI);
    else
      System.out.println("Connection failed.");
	}
}
